package com.keeping.aiimagery.entity.Untils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.keeping.aiimagery.entity.OrdersGoods;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class SignVerify {
    public static OrdersGoods notifyVerfied(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params=SignVerify.analysis(request);
        System.out.println(params);
        if(AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type)){
            OrdersGoods ordersGoods=new OrdersGoods();
            //设置金额
            String price=params.get("total_amount");
            price =price.split("\\.")[0];
            ordersGoods.setPrice(Integer.parseInt(price));
            //设置交易号
            ordersGoods.setTradeNo(params.get("out_trade_no"));
            //设置支付状态
            String status=params.get("trade_status");
            if(status.equals("TRADE_SUCCESS"))
            {
                ordersGoods.setState("支付成功");
            }
            else if(status.equals("TRADE_CLOSED"))
            {
                ordersGoods.setState("支付失败");
            }
            //设置交易时间
            String str = params.get("notify_time");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
            ordersGoods.setCreateTime(dateTime);

            Map<String,String> map=SignVerify.bodyChanage(params.get("body"));
            String goodsId=map.get("Id");
            String userId=map.get("userId");
            String integral=map.get("integral");
            //设置购买产品的Id
            ordersGoods.setGoodsId(Integer.parseInt(goodsId));
            //设置用户Id
            ordersGoods.setUserId(Integer.parseInt(userId));
            //设置积分
            ordersGoods.setIntegral(Integer.parseInt(integral));
            //设置商品名
            ordersGoods.setName(params.get("subject"));
            return ordersGoods;
        }
        else{
            return null;
        }
    }
    //同步验签
    public static boolean returnVerfied(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params=SignVerify.analysis(request);
        return AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
    }
    public static  Map<String, String> analysis (HttpServletRequest request){
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }
    //body解析为map的，拿积分和用户id;
    public static Map<String,String> bodyChanage(String body){
        body = body.substring(1, body.length() - 1);
        String stringMap = body.replaceAll("[{}\\s]", ""); //去掉大括号和空格
        Map<String, String> map = new HashMap<>();
        String[] keyValuePairs = stringMap.split(","); //以逗号分隔字符串，获取键值对数组
        for (String pair : keyValuePairs) {
            String[] entry = pair.split("="); //以等号分隔键值对，获取键和值
            map.put(entry[0], entry[1]); //将键值对加入到映射中
        }
        return map;
    }
}
